package com.yida.gwj.report.job;

import com.xxl.job.core.handler.annotation.XxlJob;
import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.domain.R;
import com.yida.common.core.utils.CheckRemoteServiceResultUtils;
import com.yida.gwj.api.service.RemoteGwjConfigService;
import com.yida.gwj.report.domain.GwjSysCalculateRate;
import com.yida.gwj.report.domain.request.GwjSettleRateRequest;
import com.yida.gwj.report.service.IGwjCalculateRateService;
import com.yida.gwj.report.service.IGwjSysCalculateRateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;


/**
 * 计息任务
 *
 * @Author: PPV
 * @Date: 2023-03-20
 */
@Slf4j
@Component
public class CalculateRateHandler {

    @Resource
    private IGwjSysCalculateRateService gwjSysCalculateRateService;

    @Resource
    private IGwjCalculateRateService gwjCalculateRateService;

    @Resource
    private RemoteGwjConfigService remoteGwjConfigService;

    private final String AUTO_CALCULATE_RATE = "auto_calculate_rate";


    @XxlJob("calculateRateHandler")
    public void syncDataHandler() {
        StringBuffer error = new StringBuffer();
        R<String> val = remoteGwjConfigService.innerGetConfigKey(AUTO_CALCULATE_RATE, SecurityConstants.INNER);
        if (CheckRemoteServiceResultUtils.isCodeFail(val)) {
            error.append(val.getMsg());
        }
        if (Boolean.parseBoolean(val.getData())) {
            List<GwjSysCalculateRate> gwjSysCalculateRates = gwjSysCalculateRateService.selectGwjSysCalculateRateListBeforeDate(LocalDate.now());
            gwjSysCalculateRates.forEach(r -> {
                //判断是否已经结算
                if (r.getDayRate() != null) {
                    try {
                        GwjSettleRateRequest request = new GwjSettleRateRequest();
                        request.setId(r.getId());
                        gwjCalculateRateService.newSettleRate(request);
                    } catch (Exception e) {
                        error.append("地区ID：").append(r.getAreaId())
                                .append("| 结算日期：").append(r.getCalculateTime())
                                .append("，结算失败：").append(e.getMessage())
                                .append("\n");
                    }
                }
            });
        }
        if (error.length() > 0 && !"null".equals(error.toString()) && !"".equals(error.toString())) {
            log.error(error.toString());
        }
    }
}
